<?php
/**
 * Geocontexter
 * @link http://code.google.com/p/geocontexter/
 * @package Geocontexter
 */

/**
 * Admin index controller
 *
 *
 * @package Geocontexter
 * @license http://www.opensource.org/licenses/bsd-license.php New BSD License
 * @author Armand Turpel <geocontexter@gmail.com>
 * @version $Rev$ / $LastChangedDate$ / $LastChangedBy$
 */

namespace Youobserve\Controller;

use Zend\View\Model\ViewModel;
use Youobserve\Controller\AbstractIdentityController;


class RecordImportController extends AbstractIdentityController
{

    protected function init($controller)
    {
        $this->initView( 'youobserve/record-import/index.phtml', true);

        $this->view->partialData = array('active_page'    => 'recordimport',
                                         'basePath'       => $this->getBaseUrl(),
                                         'logged_user'    => $this->view->logged_user);

        $this->view->error = array();
    }

    public function indexAction()
    {
        $this->sessionOffsetUnset('tmp_image_path');

		$this->view->record_status = 'insert';

        return $this->view;
    }

    public function importAction()
    {

    	$upload_folder = GEOCONTEXTER_ROOT . '/data/tmp';

    	$_error = array();

    	$fields = array('taxon'     => 1,
    	                'latitude'  => 1,
    	                'longitude' => 1,
    	                'date'      => 1,
    	                'photos'    => 5,
    	                'altitude'  => 2,
    	                'notice'    => 3);

    	$attribute = array('notice' => 2);

		if ($_FILES["csvfile"]["error"] > 0) {
		  	$_error[] = "Error: " . $_FILES["csvfile"]["error"];
		} else {
		  $this->view->file_type = $_FILES["csvfile"]["type"];

		$folder = $this->_extract($_FILES["csvfile"]["tmp_name"]);

		$RecordAdd = $this->CoreModel('RecordAdd');

			$row = 1;
			$header = 0;
			$field_map = array();
			$this->_geom = array();
			$_res = array();
			$rejected = array();

			if (($handle = fopen($folder . '/import.csv', "r")) !== FALSE) {

				while (($data = fgetcsv($handle, 0, "\t")) !== FALSE) {

					$params1   = array();
					$attribute = array();
					$photos    = false;

					if ($header == 0) {

						$num = count($data);

						for ($c=0; $c < $num; $c++) {

							$data[$c] = trim($data[$c]);

							if (isset($fields[$data[$c]])) {
								if (($fields[$data[$c]] == 1) || ($fields[$data[$c]] == 2)) {
									$field_map[$c] = $data[$c];
									$fields[$data[$c]] = 0; // field is mapped flag
								} else if ($fields[$data[$c]] == 5) {
									$field_map[$c] = $data[$c];
									$fields[$data[$c]] = 0; // field is mapped flag
								} else if ($fields[$data[$c]] == 3) {
									$field_map[$c] = $data[$c];
									$fields[$data[$c]] = 0; // field is mapped flag
								}
							}
						}

						$header = 1;
						continue;
					}

					for ($c=0; $c < $num; $c++) {

						$data[$c] = trim($data[$c]);

						if (isset($field_map[$c]) && !empty($data[$c])) {

							if ($field_map[$c] == 'notice') {
								$attribute['notice'] = $data[$c];
								//die(var_export($attribute,true));
							}

							if ($field_map[$c] == 'photos') {
								$_photo = true;
								$p = explode(",",$data[$c]);
								foreach ($p as $photo) {
								/*
									if (file_exists($upload_folder . '/' . $photo)) {
										copy($upload_folder . '/' . $photo, GEOCONTEXTER_ROOT . '/log/photo/' . $photo);
									}
									*/
									if (!file_exists($folder . '/' . $photo)) {
										$_photo = false;
										break;
									}
								}

								if (true === $_photo) {
									$photos = $data[$c];
									$params1['media_folder_hash'] = md5(time() . $photos);
								}
							}

							if ($field_map[$c] == 'date') {

								if (preg_match("/([0-9]{1,2})\/([0-9]{1,2})\/([0-9]{4})/", $data[$c], $match)) {
									$data[$c] = $match[3] . '-' . $match[2] . '-' . $match[1];
								}

								$params1['date_record_start'] = $data[$c];
							}

							if ($field_map[$c] == 'taxon') {
								if (false !== ($id_item = $this->_get_id_item( $data[$c]))) {
									$params1['id_item'] = $id_item;
								} else {
									$rejected[] = $data;
								}
							}

							if (($field_map[$c] == 'latitude') || ($field_map[$c] == 'longitude')) {
								$_func = '_add_' . $field_map[$c];
								$this->$_func($data[$c]);
							}
						}
					}

					if (!isset($params1['id_item'])) {
						continue;
					}

					$params1['geom_point'] = $this->get_geom();

				   $params2  = array('id_project'        => '1000000000000000',
									'id_context'         => '1000000000000000',
									'id_owner'           => '1000000000000007',
									'id_modifier'        => '1000000000000007',
									'id_attribute_group' => '1000000000000006',
									'id_status'          => 1000,
									'timezone'           => 'Europe/Luxembourg');

					if (count($attribute) > 1) {
						$params2['attribute_value'] = json_encode($attribute);
					}

				   $params = array_merge($params1, $params2);

				   $id_record = $RecordAdd->run( $params );

				   if ($id_record instanceof \Core\Library\Exception) {
					   return $this->error( $id_record->getMessage(), __file__, __line__);
				   }

					if ($photos !== false) {
						$this->insert_photos($folder, $id_record, $params1['media_folder_hash'], $photos);
					}

				}
				fclose($handle);
			}

		}

$fp = fopen(GEOCONTEXTER_ROOT . '/public/data/rejected.csv', 'w');

foreach ($rejected as $fields) {
    fputcsv($fp, $fields);
}

fclose($fp);


//die(var_export($_res,true));
        return $this->indexAction();
    }

    public function get_geom()
    {
		return 'ST_SetSRID(ST_MakePoint(' . $this->_geom['longitude'] . ', ' . $this->_geom['latitude'] .'), 4326)';
    }

    public function _add_latitude($str)
    {
		$this->_geom['latitude'] = $str;
    }
    public function _add_longitude($str)
    {
		$this->_geom['longitude'] = $str;
    }

    public function _get_id_item($str)
    {
		$ItemSearch = $this->CoreModel('ItemSearch');

		$params  = array('search' => $str,
		                 'search_exact' => true);

		$result = $ItemSearch->run( $params );

		if (is_array($result) && (count($result) == 1)) {
			return $result[0]['id_item'];
		} else if (is_array($result) && (count($result) > 1)) {
			$this->id_item_error = 'more_results';
			return false;
		} else {
		    $this->id_item_error = 'not found';
			return false;
		}
    }

    public function insert_photos($source_folder, $id_record, $folder, $photos)
    {
    	$photos_array = explode(",",$photos);
    	$path = GEOCONTEXTER_ROOT . '/public/data/gc_record/' . $id_record . '_' . $folder;
    	mkdir($path);
    	$path = GEOCONTEXTER_ROOT . '/public/data/gc_record/' . $id_record . '_' . $folder . '/image';
    	mkdir($path);
    	mkdir($path . '/thumbnail');

    	foreach ($photos_array as $p) {

    	   //copy($source_folder . '/' . $p, $path . '/' . $p );

		   $RecordImageAdd = $this->CoreModel('RecordImageAdd');

		   $file_info = getimagesize ( $source_folder . '/' . $p );

		   $_filesize = filesize ( $source_folder . '/' . $p );

		   $media = array('file_mime'   => $file_info['mime'],
							          'file_name'   => $p,
							          'file_size'   => $_filesize,
							          'file_height' => $file_info[1],
							          'file_width'  => $file_info[0]);

		   $params  = array('id_record'   => $id_record,
							'id_status'   => 200,
							'media'       => $media,
							'title'       => $p
						   );

		   $result = $RecordImageAdd->run( $params );

		   $ImageUpload = $this->CoreModel('ImageUpload', 'Youobserve');

		   $iparams = array('dest' => $path,
		   					'path' => $source_folder,
		                    'photo' => $p,
		                    'mime'  => $file_info['mime'],
		                    'width' => $file_info[0],
		                    'height' => $file_info[1],
		                    'new_width' => 1024,
		                    'new_height' => 800,
		                    'thumb_width' => 140);

		   $ImageUpload->run($iparams);


    	}
    }

    public function _extract($file)
    {
		$tmp_folder = GEOCONTEXTER_ROOT . '/public/data/tmp/' . uniqid('',true);
		mkdir($tmp_folder);

		$filter     = new \Zend\Filter\Decompress(array(
			'adapter' => 'Zip',
			'options' => array(
			'archive' => $file,
			'target'  => $tmp_folder,
		  )
		));

		if (!$filter->filter($file)) {
			throw new \Exception('Couldnt decompress upload archive: '.$file );
		}

		@unlink($file);

		return $tmp_folder;
    }


}
